package com.whz.clone;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * @ClassName Stack
 * @Description TODO 覆写clone方法
 * @Author hong-zhi
 * @Date 2021/5/3 19:47
 * @Version 1.0
 */
public class Stack<T> implements Cloneable {
    private T[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public Stack(int capacity) {
        this.elements = (T[]) new Object[capacity];
    }

    public Stack() {
        this.elements = (T[]) new Object[DEFAULT_INITIAL_CAPACITY];
    }
    public void push(T e) {
        ensureCapacity();
        elements[size ++] = e;
    }

    public Object pop() {
        if(size == 0) {
            throw new EmptyStackException();
        }
        Object result = elements[-- size];
        elements[size] = null;
        return result;
    }

    private void ensureCapacity() {
        if(elements.length == size) {
            elements = Arrays.copyOf(elements, 2 * size + 1);
        }
    }

    @Override
    public String toString() {
        return "Stack{" +
                "elements=" + Arrays.toString(elements) +
                ", size=" + size +
                '}';
    }

    @Override
    protected Stack<T> clone() throws CloneNotSupportedException {
        Stack result = (Stack) super.clone();
        result.elements = elements.clone();
        return result;
    }
}
